package cn.edu.ctbu.lab.service.impl;

import cn.edu.ctbu.lab.dao.CourseRepository;
import cn.edu.ctbu.lab.domain.Course;
import cn.edu.ctbu.lab.vo.BTPageDO;
import cn.edu.ctbu.lab.vo.CourseExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class CourseServiceImpl implements cn.edu.ctbu.lab.service.CourseService {

    @Autowired
    private CourseRepository courseRepository;


    @Override
    public Optional<Course> findById(Integer id){

        Optional<Course> course=courseRepository.findById(id);
        return course;
    }


    @Override
    public List<Course> findAll(){

        List<Course> myList=courseRepository.findAll();
        return myList;
    }

    @Override
    public BTPageDO<CourseExt> findByPage(int pageIndex, int pageSize){

        /*Sort sort =  Sort.by(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(pageIndex, pageSize, sort);
        Page<Course> myList=courseRepository.findAll(pageable);*/
        BTPageDO<CourseExt> pageDO=new BTPageDO<CourseExt>();


        if(pageIndex<1){
            pageIndex=1;
        }

        Integer offset=(pageIndex-1)*pageSize;
        List<CourseExt> courseExts=courseRepository.getByPage(offset,pageSize);
        Integer total=courseRepository.getByPageCount();
        pageDO.setRows(courseExts);
        pageDO.setTotal(total);

        return pageDO;

    }




    @Override
    public Course add(Course course){
        courseRepository.save(course);
        return course;
    }

    @Override
    public Course update(Course course){

        courseRepository.save(course);
        return course;
    }


    @Override
    public int delete(Course course){

        try{

            courseRepository.delete(course);
        }catch (Exception e){

            //throw  e;
            return -1;
        }
        return 1;
    }

    @Override
    public  int delete(Integer id){
        Course course=courseRepository.getOne(id);

        return delete(course);

    }


}
